// src/utils/permission.js
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'

/**
 * 检查用户是否具有指定权限
 * @param {Array} value - 需要检查的权限数组
 * @returns {Boolean} - 是否具有权限
 * @example v-permission="['admin','editor']"
 */
export function checkPermission(value) {
  const userStore = useUserStore()
  const { permissions } = storeToRefs(userStore)

  if (value && Array.isArray(value) && value.length > 0) {
    const permissionRoles = value
    // 检查用户是否具有传入的权限之一
    const hasPermission = permissions.value.some(permission => {
      return permissionRoles.includes(permission)
    })
    return hasPermission
  } else {
    console.error(`需要指定权限角色! 如 v-permission="['admin','editor']"`);
    return false
  }
}

/**
 * 创建自定义权限指令
 * @example v-permission="['admin']"
 */
export function createPermissionDirective(app) {
  app.directive('permission', {
    mounted(el, binding) {
      const { value } = binding
      const hasPermission = checkPermission(value)

      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  })
}